package com.xb.system.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xb.system.utils.JwtUtil;
import com.xb.system.utils.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(JwtInterceptor.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求路径，帮助调试
        String requestURI = request.getRequestURI();
        logger.info("拦截请求: {} {}", request.getMethod(), requestURI);
        
        // 允许OPTIONS请求通过(跨域预检请求)
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            logger.info("OPTIONS预检请求放行");
            return true;
        }
        
        // 首先检查是否是允许匿名访问的路径
        if (requestURI.startsWith("/auth/") ||  // 放行所有认证相关接口
            requestURI.startsWith("/agreement/") ||  // 放行协议接口
            requestURI.equals("/invite/notify-register") ||
            requestURI.endsWith("/admin/system/sysDoc/download-template") ||
            requestURI.contains("/public/template/download") ||
            requestURI.startsWith("/profile/") ||  // 放行所有静态资源（图片等）
            requestURI.startsWith("/images/") ||   // 放行图片资源
            requestURI.startsWith("/checksystem/advertisement") ||  // 放行广告相关接口
            requestURI.startsWith("/payment/") ||  // 放行支付回调
            requestURI.equals("/error")) {  // 放行错误处理端点
            logger.info("匿名访问接口放行: {}", requestURI);
            return true;
        }
        
        // 检查认证头
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 移除 "Bearer " 前缀
            try {
                if (jwtUtil.validateToken(token)) {
                    Long userId = jwtUtil.getUserIdFromToken(token); // 解析 userId
                    UserContext.setUserId(userId); // 存储到 ThreadLocal
                    logger.info("UserId {} authenticated successfully", userId);
                    return true;
                } else {
                    logger.warn("无效或过期token: {}", requestURI);
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效或过期 token");
                    return false;
                }
            } catch (Exception e) {
                logger.error("Token 验证失败: {}", e.getMessage());
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "token 验证异常");
                return false;
            }
        } else {
            logger.warn("缺少Authorization头: {}", requestURI);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "缺少有效的 Authorization 头");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear(); // 请求完成后清理 ThreadLocal
    }
}